<template>
  <div v-loading="loading" class="login" element-loading-text="登录中...">
    123123
  </div>
</template>

<script>
import { getCodeImg, getTenant, captchaImageShow, getTenantInfo } from '@/api/login'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { getLanguage } from '@/api/dev/language/sysLanguage'
import { Notification } from 'element-ui'
import { getAuthorizeURL } from '@/api/qywx/qywx'

export default {
  name: 'WxLogin',
  components: {
  },
  data() {
    return {
      codeUrl: '',
      cookiePassword: '',
      // 是否多租户模式
      tenant: 'false',
      // 登录失败次数
      loginFailNum: 0,
      // 等待框
      formLoadIng: false,
      loginForm: {
        username: '',
        password: '',
        tenantCode: '',
        code: '',
        uuid: '',
        phonenumber: ''
      },
      rememberMe: true,
      loading: true,
      redirect: undefined,
      tenantCompanyInfo: {
        logo: undefined,
        name: undefined,
        width: undefined,
        height: undefined
      }
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        if (route.query.code) {
          this.handleLogin(route.query.code, route.query.tenantCode)
        } else {
          this.getAuthorizeURL()
        }
      },
      immediate: true
    }
  },
  created() {
    /* this.getCode()
    this.getCookie()
    // 查询是否多租户
    this.getTenant()
    // 获取租户logo和名称
    this.getTenantInfo()*/
    // this.getTenant()
    // this.getCode()
    // this.getCookie()
    // this.singleSignOn()
  },
  mounted() {
    // 绑定登录页回车键登录事件
    window.addEventListener('keydown', this.keyDown)
  },
   // 增加登录页回车键登录功能
  methods: {
    getAuthorizeURL() {
      var tenantCode = this.$route.query.tenantCode
      getAuthorizeURL(tenantCode).then(res => {
        window.location.href = res.data
      })
    },
    toOpen(href) {
      window.open(href, '_blank')
    },
    keyDown(e) {
      if (e.keyCode === 13) {
        this.handleLogin()
      }
    },
    chat() {
      if (this.$refs.contactUs?.visible !== undefined) {
        this.$refs.contactUs.visible = true
      }
    },
    toReset() {
      this.$router.push({ path: '/recoverpw' })
    },
    getCode() {
      if (this.loginFailNum >= 3) {
        getCodeImg().then(res => {
          this.codeUrl = 'data:image/gif;base64,' + res.datas.img
          this.loginForm.uuid = res.datas.uuid
        })
      }
    },
    getCookie() {
      const username = Cookies.get('username')
      const password = Cookies.get('password')
      const tenantCode = Cookies.get('tenantCode')

      debugger
      var tenantCompanyInfo = window.localStorage.getItem('tenantCompanyInfo')
      if (tenantCompanyInfo) {
        try {
          this.tenantCompanyInfo = JSON.parse(tenantCompanyInfo)
        } catch (e) {
          console.log(e)
        }
      }

      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        tenantCode: tenantCode === undefined ? undefined : tenantCode
      }
      if (username === undefined) {
        this.rememberMe = false
      }
    },
    // 获取是否展示验证码
    captchaImageShow() {
      if (this.loginForm.username !== undefined && this.loginForm.username !== '') {
        captchaImageShow(this.loginForm.username).then(res => {
          if (res.data) {
            this.loginFailNum = 3
            this.getCode()
          }
        })
      }
    },
    /**
     * 获取是不是多租户模式
     */
    getTenant() {
      this.formLoadIng = true
      getTenant().then(res => {
        if (res !== undefined) {
          this.tenant = res.data
        }
      })
    },
    // 获取当前租户的logo和名称
    getTenantInfo(tenantCode) {
      // 从url中获取租户code
      if (tenantCode === undefined) {
        tenantCode = this.$route.query.tenantCode
      }
      if (tenantCode !== undefined) {
        this.loginForm.tenantCode = tenantCode
      }
      getTenantInfo(this.loginForm.tenantCode).then(res => {
        if (res.data !== null) {
          this.tenantCompanyInfo.logo = res.data.productLogo
          this.tenantCompanyInfo.name = res.data.productName
          this.tenantCompanyInfo.width = res.data.productLogoWidth
          this.tenantCompanyInfo.height = res.data.productLogoHeight
        } else {
          this.tenantCompanyInfo = { logo: undefined, name: undefined, width: undefined, height: undefined }
        }
        debugger
        console.log(JSON.stringify(this.tenantCompanyInfo))
        window.localStorage.setItem('tenantCompanyInfo', JSON.stringify(this.tenantCompanyInfo))
        this.formLoadIng = false
      }).catch(() => {
        this.tenantCompanyInfo = { logo: undefined, name: undefined, width: undefined, height: undefined }
        this.formLoadIng = false
      })
    },
    // 更新失败次数
    addLoginFailNum() {
      this.loginFailNum++
    },
    getLanguage() {
      getLanguage(undefined, this.loginForm.tenantCode).then(response => {
        var localStorage = window.localStorage.getItem('language')
        if (localStorage === undefined || localStorage === null || localStorage === 'null') {
          localStorage = 'zh_cn'
        }
        this.$i18n.vm.messages[localStorage] = response.languageData
        // 修改国际化词条
        window.localStorage.setItem('language_' + localStorage, JSON.stringify(response.languageData))
        window.localStorage.setItem('language', localStorage)
        this.$i18n.locale = localStorage
      })
      this.getTenantInfo(this.loginForm.tenantCode)
    },
    singleSignOn() {
      console.log('单点登录')

          this.loading = true
          if (this.rememberMe) {
            Cookies.set('username', this.loginForm.username, { expires: 30 })
            Cookies.set('password', encrypt(this.loginForm.password), { expires: 30 })
            Cookies.set('tenantCode', this.loginForm.tenantCode, { expires: 30 })
          } else {
            Cookies.remove('username')
            Cookies.remove('password')
            Cookies.remove('tenantCode')
          }
          this.loginForm.idToken = this.$route.query.id_token

          this.$store
            .dispatch('LoginJump', this.loginForm)
            .then(() => {
              this.getLanguage()
              this.$router.push({ path: '/index' || '/', name: '首页', params: { once: 1 }})
              this.$store.state.permission.leftActive = this.$store.state.permission.navActive = '999'
            })
            .catch((err) => {
              if (err === '验证码已失效') {
                this.loading = false
                this.loginFailNum = 3
                this.getCode()
              } else {
                this.loading = false
                // 更新登录失败次数
                this.addLoginFailNum()
                this.getCode()
              }
            })
    },
    handleLogin(authCode, tenantCode) {
      console.log('登录', this.loginForm)
      this.loading = true
      this.$store
        .dispatch('WxLogin', { authCode, tenantCode })
        .then(() => {
          this.loginForm.tenantCode = tenantCode
          this.getLanguage()
          this.$router.push({ path: '/index' || '/', name: '首页', params: { once: 1 }})
          this.$store.state.permission.leftActive = this.$store.state.permission.navActive = '999'
        })
        .catch((err) => {
          Notification.info({
            title: this.$t(err)
          })
        })
    }

  }
}
</script>
<style scoped lang="scss">
.pub-icon{
  position: fixed;
  right: 20px;
  top: 20px;
  display: flex;
  align-items: center;
  font-weight: bold;
  background-image: linear-gradient(0deg, #04c5dc, #069cf3);
  background-clip:text;
  -webkit-background-clip:text;
  color: transparent;
  .pub{
    display: inline-block;
    width: 25px;
    height: 25px;
    background-size: cover;
    background-image: url();
  }
}
.login .el-login-footer{
  height: unset!important;
  line-height: unset!important;
  bottom: 5px!important;
  .links{
    margin: 0;
    margin-bottom: 5px;
    a{
      text-decoration: underline;
    }
  }
}
</style>
